package com.ninetaildemonfox.zdl.socialproject.wxapi;


import android.content.Intent;
import android.os.Bundle;

import com.ninetaildemonfox.zdl.socialproject.base.BaseActivity;
import com.ninetaildemonfox.zdl.socialproject.R;
import com.ninetaildemonfox.zdl.socialproject.data.entity.EventMessage;
import com.ninetaildemonfox.zdl.socialproject.utils.ToastUtil;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

/**
 * @author txunda_lh
 * @date 2017/8/1.
 */
public class WXPayEntryActivity extends BaseActivity implements IWXAPIEventHandler {

    private IWXAPI api;

    @Override
    protected int getLayoutResource() {
        return R.layout.aty_wx_pay;
    }

    @Subscribe
    @Override
    public void onInitialization(Bundle bundle) {
        api = WXAPIFactory.createWXAPI(this, "wx345b17f7f69967f1");
        api.handleIntent(getIntent(), this);
        EventBus.getDefault().register(me);
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }


    @Override
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(me);
        super.onDestroy();
    }

    @Override
    public void onResp(BaseResp resp) {
        int code = resp.errCode;
        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            if (code == 0) {
                Intent intent = new Intent();
                intent.setAction("wx_pay");
                intent.putExtra("errCode", "0");
                sendBroadcast(intent);
//                ToastUtil.show("支付成功");
                EventBus.getDefault().post(new EventMessage("支付成功"));
                finish();
            } else if (code == -1) {
                ToastUtil.show("支付错误");
                finish();
            } else if (code == -2) {
                ToastUtil.show("支付取消");
                finish();
            }
        }
    }
}